import ACT from '../pages/actionType'
import { ajax } from '../utils/axios'

export default store => next => action => {
  const { dispatch, getState } = store
  /*如果dispatch来的是一个function，此处不做处理，直接进入下一级*/
  if (typeof action === 'function') return action(dispatch, getState)
  /*解析action*/
  const { promise, types, afterSuccess, ...rest } = action

  /*没有promise，证明不是想要发送ajax请求的，就直接进入下一步啦！*/
  if (!action.promise) return next(action)

  /**
   * 分解异步请求的三个阶段
   */
  const REQUEST = ACT.REQUEST
  const SUCCESS = types[0]
  const FAILURE = types[1] || ACT.FAILURE
  /**
   * 发出请求时
   */
  // next({
  //   ...rest,
  //   type: REQUEST
  // });

  /**
   * 发出请求，成功时
   */
  const onFulfilled = result => {
    next({
      ...rest,
      payload: { ...result.data },
      type: SUCCESS
    })
    if (afterSuccess) {
      afterSuccess(result, dispatch, getState)
    }
  }
  /**
   * 发出请求，失败时
   */
  const onRejected = error => {
    next({
      ...rest,
      error,
      type: FAILURE
    })
  }

  return promise(ajax)
    .then(onFulfilled, onRejected)
    .catch(error => {
      console.error('请求错误[中间件]', error)
      onRejected(error)
    })
}
